package com.gitee.mqttclient.callback;

import com.gitee.mqttclient.client.PahoMqttClient;
import com.gitee.mqttclient.client.TopicInfo;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 回调基类
 *
 * @author thc
 */
public abstract class PahoMqttCallback implements MqttCallbackExtended {

    private static final Logger LOG = LoggerFactory.getLogger(PahoMqttCallback.class);

    /**
     * 连接次数
     */
    protected final AtomicInteger connectTimes = new AtomicInteger();

    private PahoMqttClient mqttClient;

    /**
     * 连接成功会进入到这里. <br />
     * 如果设置了<code>PahoMqttClient.automaticReconnect(true)</code>，断开连接后会自动进入这里<br />
     * 如果设置<code>PahoMqttClient.automaticReconnect(false)</code>，
     * {@link org.eclipse.paho.client.mqttv3.MqttCallback#connectionLost(Throwable)}实现重连功能
     *
     * @param reconnect
     * @param serverURI
     */
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        int connectTimes = this.connectTimes.incrementAndGet();
        LOG.info("连接broker成功, broker={}, clientId={}, username={}, cleanSession={}, automaticReconnect={}, 连接次数={}",
                mqttClient.getBroker(),
                mqttClient.getClientId(),
                mqttClient.getUsername(),
                mqttClient.isCleanSession(),
                mqttClient.isAutomaticReconnect(),
                connectTimes
        );
        // 只订阅有主题，发布不走这段代码
        if (!this.mqttClient.getTopicInfos().isEmpty()) {
            this.mqttClient.subscribeTopics(topicInfo -> {
                LOG.info("订阅topic成功, clientId={}, topic={}, qos={}",
                        mqttClient.getClientId(), topicInfo.getTopic(), topicInfo.getQos());
            }, topicSubscribeException -> {
                MqttException mqttException = topicSubscribeException.getMqttException();
                TopicInfo topicInfo = topicSubscribeException.getTopicInfo();
                LOG.error("订阅topic失败，clientId={}, topic={}, qos={}",
                        mqttClient.getClientId(), topicInfo.getTopic(), topicInfo.getQos(), mqttException);
            });
        }
    }

    public PahoMqttClient getPahoMqttClient() {
        return mqttClient;
    }

    public void setPahoMqttClient(PahoMqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }
}